<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- //添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" class="addCateBtn" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen"></i>
          <!-- <pre>{{scope.row}}</pre> -->
          <i class="el-icon-error" v-else style="color:green"></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" v-else="scope.row.cat_level===2">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="caozuo" slot-scope="scope">
          <!-- <pre>{{scope.row}}</pre> -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3,5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 编辑分类 -->
    <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="30%">
      <el-form :model="editForm" ref="editFormRef">
        <el-form-item label="修改分类">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialoHandle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加分类 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form :model="addCateForm" :rules="addCateRules" ref="addCateRef" label-width="100px">
        <!-- 分类名称 -->
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <!-- 父级分类 -->
        <!-- :options 可选项数据源，键名可通过 Props 属性配置 -->
        <el-form-item label="父级分类：">
          <el-cascader
            :options="parentCateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      cateList: [],
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          prop: "cat_deleted",
          type: "template",
          template: "isok"
        },
        {
          label: "排序",
          prop: "cat_level",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "caozuo"
        }
      ],
      total: 0,
      // 编辑对话框默认不显示
      editDialogVisible: false,
      // 点击编辑按钮，获取到该数据
      editForm: {},
      addCateDialogVisible: false,
      addCateForm: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0
      },
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      // 父级分类的列表   可选项数据源，键名可通过 Props 属性配置
      parentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 选中的父级分类的Id数组
      selectedKeys: []
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 商品分类数据列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类数据列表失败");
      }
      // console.log(res);

      this.cateList = res.data.result;
      // console.log(this.cateList);
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      //刷新一下页面
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      //刷新一下页面
      this.getCateList();
    },
    // 编辑分类 根据 id 查询分类
    async editCate(id) {
      // 获取到分类名称对应的id
      // console.log(id);
      // 根据 id 查询分类发送请求
      const { data: res } = await this.$http.get(`categories/${id}`);
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("获取数据失败");
      }
      this.editForm = res.data;
      // console.log(this.editForm);

      this.editDialogVisible = true;
    },
    // 编辑提交分类
    async editDialoHandle() {
      // console.log(id);

      var { data: res } = await this.$http.put(
        `categories/${this.editForm.cat_id}`,
        {
          cat_name: this.editForm.cat_name
        }
      );
      console.log(this.editForm.cat_id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("修改商品分类失败");
      }
      // 修改成功以后
      // 提示用户
      this.$message.success("修改商品分类成功");
      // 刷新页面
      this.getCateList();
      // 关闭对话框
      this.editDialogVisible = false;
    },
    // 删除对话框
    async deleteCate(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该商品分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消了商品分类删除");
      }
      const { data: res } = await this.$http.delete("categories/" + id);
      console.log(res);

      if (res.meta.status !== 200) {
        return this.$message.error("删除商品分类失败");
      }
      console.log(res);
      this.$message.success("删除商品分类成功");
      this.getCateList();
    },

    addCate() {
      this.addCateDialogVisible = true;
      this.getParentCateList();
    },
    // 商品分类数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: {
          type: 2
        }
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("获取分类数据失败");
      }
      this.parentCateList = res.data;
      // console.log(this.parentCateList);
    },
    parentCateChanged() {
      console.log(this.selectedKeys);
      // 如果选中的父级分类的Id数组的长度大于0
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys.length - 1;
        this.addCateForm.cat_level = this.selectedKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    // 点击确定按钮后，预验证  再发送请求  添加分类
    addCateSure() {
      console.log(this.addCateForm);
      // 在点击确定按钮之前，先对表单经行预验证   如果校验通过则是true，如果没有通过则是false

      this.$refs.addCateRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 发送请求
        const { data: res } = await this.$http.post("categories", {
          cat_pid: this.addCateForm.cat_pid,
          cat_name: this.addCateForm.cat_name,
          cat_level: this.addCateForm.cat_level
        });
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("创建分类失败");
        }
        this.$message.success("创建分类失败");
        this.getCateList();
        this.addCateDialogVisible=false
      });
    },
    // 重置表单
    addCateDialogClosed() {
      this.$refs.addCateRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = "";
      this.addCateForm.cat_level = "";
    }
  }
};
</script>



<style lang="less" scoped>
.addCateBtn {
  margin-bottom: 15px;
}
</style>